package com.appsindy.common.converter;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Locale;
import java.util.Map;
import org.apache.struts2.util.StrutsTypeConverter;

public class DateConverter extends StrutsTypeConverter {
    
        public static final String formatS = "dd/MM/yyyy";
	public static final String formatL = "dd/MM/yyyy HH:mm:ss";
        public static final String formatRex = "(0[1-9]|[12][0-9]|3[01])[- /.](0[1-9]|1[012])[- /.](19|20)\\d\\d";//dd/MM/yyyy format.
	public Object convertFromString(Map ctx, String[] value, Class arg2) {

		if (value[0] == null || value[0].trim().equals("")) {
			return null;
		}
                SimpleDateFormat sdf = null;
                if(value[0].matches(formatRex)){
                     sdf = new SimpleDateFormat(formatS, Locale.US);
                } else {
                     sdf = new SimpleDateFormat(formatL, Locale.US);
                }
		
		try {
			return sdf.parse(value[0]);
		} catch (ParseException pe) {
                        System.out.println("=================================== Exception parse date fails. value[0] =" + value[0]);
                        System.out.println("=================================== Exception parse date fails. class =" + arg2);
			pe.printStackTrace();
		} catch (Exception pe) {
                    System.out.println("=================================== Exception parse date fails. value[0] =" + value[0]);
                    System.out.println("=================================== Exception parse date fails. class =" + arg2);
                    pe.printStackTrace();
                }
                return null;
	}

	public String convertToString(Map ctx, Object data) {
		SimpleDateFormat sdf = new SimpleDateFormat(formatS, Locale.US);
		return sdf.format(data);
	}
        
        public static void main( String args[] ) {
            String a = "12/11/2009";
            //String b = "[.-()/.|\";
          
            System.out.println(String.format(formatL, a));
            System.out.println(a);
         // System.out.println(a.matches(f));
        }
}